#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

void drawapp (Mat result, Mat img2)//绘制轮廓
{
    for (int i = 0; i < result.rows;i++)
    {
    //最后一个坐标点与第一个坐标点相连
    if (i ==result.rows-1)
    {
    Vec2i pointl = result.at<Vec2i>(i);
    Vec2i point2 = result.at<Vec2i>(0);
    line(img2, pointl, point2, Scalar(0,0,255),2,8, 0);
    break;
    }
    Vec2i point1 = result.at<Vec2i>(i);
    Vec2i point2 = result.at<Vec2i>(i + 1);
    line(img2, point1, point2, Scalar(0,0, 255),2,8, 0);
    }
}

int main()
{
//     Mat img=imread("/home/lwj/opencv.21/0.jpg");
//     if(img.empty())
//     {
//         cout<<"no"<<endl;
//         return -1;
//     }
//     Mat canny,image,imag;
//     Canny (img, canny, 80, 160, 3, false);//滤波

//     //膨胀运算
//     Mat kernel = getStructuringElement(0, Size(3,3));
//     //erode(canny,canny,kernel);
//     dilate(canny, canny, kernel);
//    //cvtColor(canny,image,COLOR_BGR2GRAY);
//     threshold(canny,imag,50,255,THRESH_BINARY_INV);
//     imshow("ezh",imag);
//     //轮廓发现与绘制
Mat img=imread("/home/lwj/opencv.21/0.jpg");
if(img.empty())
{
    cout<<"no"<<endl;
    return -1;
}
Mat image,canny,imgv,imge,imgel,imag;
cvtColor(img, image, COLOR_BGR2GRAY);
Mat kernel = getStructuringElement(0, Size(3,3));
//erode(img,imge,kernel);
threshold(image, imgv ,245 ,255, THRESH_BINARY);
erode(imgv,imge,kernel);
GaussianBlur(imge,canny,Size(3,3),4);//高斯滤波
Laplacian(canny,imag,-1);//高斯化拉普
imshow("ll",imag);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;

    findContours (imag, contours, hierarchy,0,2,Point());
    //绘制多边形
    for (int t = 0; t < contours.size();t++)
    {
        //用最小外接矩形求取轮廓中心
        RotatedRect rrect =minAreaRect(contours[t]);
        Point2f center = rrect.center;
        circle(img, center, 2, Scalar(0, 255, 0),2,8, 0);
        Mat result;
        approxPolyDP(contours[t], result, 4, true);//多边形轮廓逼近
        drawapp(result, img);
        //cout << "corners :" << result.rows << endl;
        //判断形状和绘制轮廓
        if (result.rows == 3)
        {
            putText(img, "triangle", center, 0, 1, Scalar(0, 255, 0), 1, 8);
        }
        if (result.rows == 4)
        {
            putText(img, "rectangle",center, 0, 1, Scalar(0,255, 0), 1, 8);
        }
        if (result.rows == 8)
        {
            putText(img,"poly-8", center, 0, 1, Scalar(0, 255, 0),1, 8);
        }
        if (result.rows > 12)
        {
             putText(img, "circle", center, 0, 1, Scalar(0, 255,0),1,8);
        }

         // 遍历 contours[i] 的子轮廓
        for(int j = hierarchy[t][2]; j != -1; j = hierarchy[j][0])
        {
            contours[j];// contours[t]的子轮廓
            imshow("子轮廓",contours);
        }
    }
        imshow("result",img);
    waitKey(0);
    return 0;
}